package com.yuzhantao.collection.sensorflow.request;

import javax.jms.ConnectionFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.common.reflect.TypeToken;
import com.yuzhantao.collection.core.message.MessageHandleContext;
import com.yuzhantao.collection.sensorflow.message.RootMessage;
import com.yuzhantao.collection.sensorflow.request.handle.LedCommandHandle;

@Component
public class ServerCommandListener  extends MessageListenerAdapter{
	private static Logger logger = LogManager.getLogger(ServerCommandListener.class.getName());
	// 通过策略模式处理不同的信息
	private MessageHandleContext<RootMessage,Object> messageHandleContent;
	@Autowired
	protected LedCommandHandle ledCommandHandle;
	public ServerCommandListener(){
		super();
		this.messageHandleContent=new MessageHandleContext<>();
		this.messageHandleContent.addHandleClass(ledCommandHandle);
	}
	
	@SuppressWarnings("serial")
	@JmsListener(destination = "DAIO", containerFactory = "jmsListenerServerCommandTopic")
    public void receiveMessage(String message) {
		try {
			RootMessage rm = JSON.parseObject(message,new TypeToken<RootMessage>(){}.getType());
			this.messageHandleContent.handle(rm);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	@Bean
	public JmsListenerContainerFactory<?> jmsListenerServerCommandTopic(ConnectionFactory activeMQConnectionFactory) {
		DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
		bean.setPubSubDomain(true);
		bean.setConnectionFactory(activeMQConnectionFactory);
		return bean;
	}
}
